package com.jhws.sys.cms.service;

import com.jhws.common.Page;
import com.jhws.core.db.BaseDao;
import com.jhws.core.exception.BizException;
import com.jhws.sys.cms.bo.RichText;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings({"SingleStatementInBlock", "Duplicates"})
@Service
public class RichTextService {
    @Resource
    private BaseDao BaseDao;
    @Resource
    private ITblUserDimService userDimService;

    /**
     * 保存富文本
     *
     * @param ueEditor 富文本
     */
    public void saveUeditor(RichText ueEditor) {
        TblUserDimBo userDimBo = userDimService.currentUser();
        ueEditor.setUser(userDimBo.getLogName());
        ueEditor.setUpdateTime(new Date());
        if (ueEditor.getId() == null) {
            throw new BizException("ID错误，前端为上传ID！");
        } else {
            BaseDao.h().saveOrUpdate(ueEditor);
        }
    }

    /**
     * 查询副文本列表
     *
     * @param param Map
     * @return 副文本列表
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> queryUeditorList(Map param) {
        boolean isNotPage = MapUtils.getBooleanValue(param, "isNotPage");
        String sql = "SELECT * " + " FROM cms_rich_text WHERE 1=1 ";
        TblUserDimBo userInfo = userDimService.currentUser();
        sql += " and user ='" + userInfo.getLogName() + "'";

        String queryContent = MapUtils.getString(param, "queryContent", "");
        if (StringUtils.isNotEmpty(queryContent)) {
            sql += "and (description like '%" + queryContent + "%' or content like '%" + queryContent + "%') ";
        }

        sql += " order by update_time desc";
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list;
        if (isNotPage) {
            list = BaseDao.j().queryForList(sql);
        } else {
            Page p = BaseDao.queryPage(sql, Map.class);
            list = p.getList();
            result.put("size", p.getTotalNumber());
        }
        result.put("list", list);
        result.put("ret_code", 1);
        return result;
    }

    /**
     * 删除副文本信息
     *
     * @param ueEditor 副文本ID
     */
    public void deleteUeditor(RichText ueEditor) {
        BaseDao.h().delete(ueEditor);
    }

    /**
     * 查询副文本信息
     *
     * @param id 副文本ID
     */
    public RichText queryUeditorInfo(String id) {
        return BaseDao.h().get(RichText.class, id);
    }
}
